import cartApi from '../../api/cart.api';

const state={
  data:[],
  cart:[]
};

const getters={
  cart: (state: any) => {
    return state.cart;
  },

  data: (state: any) => {
    return state.data;
  },
};

const actions={
  async getCarts({commit}:any,params: any={}){
    const data=await cartApi.getCarts(params);
    commit('setData', data);
    const arr=[];
    data.data.forEach((v,i) => {
      let isPush=false;
      if(arr.length>0){
        arr.forEach((v1,i1) => {
          if(v1.product_id==v.product_id){
            v1.number+=v.number;
            isPush=true;
          }
        });
      }
      if(!isPush){
        arr.push(v);
      }
    });
    commit('setCart', arr);
  }
};

const mutations={
  setData(state: any, data: any){
    state.data = data;
  },

  setCart(state: any, data: any){
    state.cart=data;
  }
};

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}